package com.info.zhiduoduo.common.aliyunsdk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.aliyun.ocr_api20210707.models.RecognizeBankCardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.tea.TeaException;
import com.baidubce.util.JsonUtils;
import com.google.gson.JsonObject;
import com.info.zhiduoduo.common.aliyunsdk.pojo.BankMessage;
import com.info.zhiduoduo.common.aliyunsdk.pojo.IdMessage;
import com.info.zhiduoduo.common.baidusdk.domain.OcrBankcardResult;
import com.info.zhiduoduo.common.baidusdk.domain.OcrIdcardResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.terracotta.statistics.Sample;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author tianyonghong
 * @create 2023/11/28
 */
@Service
@Slf4j
public class RecognizeIdcardService {

//    @Resource
//    private AliYunIdCardConfig aliYunIdCardConfig;

    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId("LTAI5tPBkrmS3Q8MDkET5sFD")
//                .setAccessKeyId(aliYunIdCardConfig.getAccessKey())
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret("VnEiLaXy7VkQ2axc6vG2GCmO1lrY4G");
//                .setAccessKeySecret(aliYunIdCardConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    public static OcrIdcardResult checkIdCard(File file) {
        try {
            com.aliyun.ocr_api20210707.Client client = createClient();
            com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest request = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest();
            request.setBody(new FileInputStream(file));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 复制代码运行请自行打印 API 的返回值
            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(request, runtime);
//            response.getBody().getData();
            log.info("idcard response code：{},message:{}" + response.getBody().toString());
            //成功没有code
            if(StringUtils.isBlank(response.getBody().getCode())){
                log.info("身份证识别成功!");
                JSONObject data1 = JSONObject.parseObject(response.getBody().getData());
                JSONObject data2 = JSONObject.parseObject(data1.get("data").toString());
                IdMessage message = new IdMessage();
                if(data2.get("face") != null) {
                    JSONObject face = JSONObject.parseObject(data2.get("face").toString());
                    message = JSON.parseObject(face.get("data").toString(), IdMessage.class);
                } else if(data2.get("back") != null){
                    JSONObject face = JSONObject.parseObject(data2.get("back").toString());
                    message = JSON.parseObject(face.get("data").toString(), IdMessage.class);
                }
                OcrIdcardResult result = new OcrIdcardResult();
                result.setIdno(message.getIdNumber());
                result.setName(message.getName());
                result.setSex(message.getSex());
                result.setBirth(message.getBirthDate());
                result.setAddr(message.getAddress());
                result.setNationality(message.getEthnicity());

                result.setAuthority(message.getIssueAuthority());
                result.setInvalidDate(message.getValidPeriod());
                return result;
            }else {
                log.info("身份证识别失败：" + response.getBody().getMessage());
            }
        } catch (TeaException error) {
            // 错误 message;诊断地址
            log.error("idcard TeaException message:{},Recommend:{}" , error.getMessage(),error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message 诊断地址
            log.error("idcard Exception message:{},Recommend:{}" , error.getMessage(),error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    public static BankMessage checkBankCard(File file) {
        try {
            com.aliyun.ocr_api20210707.Client client = createClient();
            com.aliyun.ocr_api20210707.models.RecognizeBankCardRequest request = new com.aliyun.ocr_api20210707.models.RecognizeBankCardRequest();
            request.setBody(new FileInputStream(file));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 复制代码运行请自行打印 API 的返回值
            RecognizeBankCardResponse response = client.recognizeBankCardWithOptions(request, runtime);
//            response.getBody().getData();
            log.info("bankcard response：" + response.getBody().toString());
            //成功没有code
            if(StringUtils.isBlank(response.getBody().getCode())){
                log.info("银行卡识别成功!");
                JSONObject dataObj = JSONObject.parseObject(response.getBody().getData());
                BankMessage message = JSON.parseObject(dataObj.get("data").toString(), BankMessage.class);
                return message;
            }else {
                log.info("身份证识别失败：" + response.getBody().getMessage());
            }
        } catch (TeaException error) {
            // 错误 message;诊断地址
            log.error("bankcard TeaException message:{},Recommend:{}" , error.getMessage(),error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message 诊断地址
            log.error("idcard Exception message:{},Recommend:{}" , error.getMessage(),error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }
}
